package com.kklldog.core.task;

import java.lang.reflect.Method;

import com.kklldog.core.task.TaskListener;
import com.kklldog.core.task.TaskParams;

import android.os.AsyncTask;
import android.util.Log;

/** 
 * @author mj.zhou 
 * @version create：2013-12-4 下午3:25:28 
 * 异步调用基类 T为返回值类型
 */
public abstract class BaseAsyncTask extends AsyncTask<TaskParams, Object, TaskResult<?>> {
	
	private TaskListener listener;
	
	protected abstract String getClassName();
	
  /**
   * 根据方法名反射执行方法
   * @param params
   * @return
 * @throws Exception 
   */
	protected TaskResult<?> excuteMethodByName(TaskParams... params) 
    {
    	TaskParams param= params[0];
    	String clazzName = getClassName();
    	if(param.getExecMethodName()==null||param.getExecMethodName().trim().isEmpty())
    	{
    		//throw new Exception("未指定执行的方法名");
    		TaskResult<String> result = new TaskResult<String>();
    		result.setIsSuccess(false);
    		result.setErrorMessage("未设置执行方法");
    		
    		return result;
    	}
    	Class<?> clazz=null;
		try {
			clazz = Class.forName(clazzName);
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
        try{
            Method method=clazz.getMethod(param.getExecMethodName(),TaskParams.class);
            return  (TaskResult<?>)method.invoke(this,param);
             
        }catch (Exception e) {
        	Log.v("Task", clazzName);
            e.printStackTrace();
        }
		return null;
    }

	@Override
	protected TaskResult<?> doInBackground(TaskParams... params) {
		// TODO Auto-generated method stub
		return excuteMethodByName(params);
	}
	@Override
	protected void onCancelled() {
		// TODO Auto-generated method stub
		super.onCancelled();
		if(listener!=null)
		{
			listener.onCancelled(this);
		}
	}

	@Override
	protected void onPostExecute(TaskResult<?> result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		if(listener!=null)
		{
			listener.onPostExecute(this, result);
		}
	}
	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		if(listener!=null)
		{
			listener.onPreExecute(this);
		}
	}



	public TaskListener getListener() {
		return listener;
	}



	public void setListener(TaskListener listener) {
		this.listener = listener;
	}
   
	
	
}
